import { useEffect, useState } from "react";
// 引入antd的样式
import {
  Button,
  Form,
  Input,
  Select,
  Table,
  Card,
  Col,
  Row,
  message,
} from "antd";
import { useNavigate } from "react-router-dom";
// 引入配置
import {
  PagingListRequest,
  hospitalListContentType,
  hospitalDateType,
  regionReturnResultType,
} from "@/api/hospital/model/hospitalListTypes";
// 引入api请求
import {
  SendHospitalListRequest,
  ProvinceInformationRequest,
  GetRegionalDataRequest,
  ChangeStatusRequest,
} from "@/api/hospital/hospitalList";
export default function HospitalList() {
  //通过Form组件上的一个useForm方法,可以创建实例,然后在某一个Form组件上添加一个form属性,值为当前实例,那么Form表单和当前的form实例就关联起来了
  const [form] = Form.useForm();
  // 获取重定向的组件
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  // 控制当前页码的状态
  const [page, setPage] = useState(1);
  // 控制总数据的数量
  const [total, setTotal] = useState(0);
  // 控制当前每条显示的条数
  const [limit, setLimit] = useState(3);
  //控制查询时用户输入的表单参数
  const [paramsList, setParamsList] = useState<PagingListRequest>({});
  // 控制渲染表单渲染的数据
  const [tableData, setTableDate] = useState<hospitalListContentType>([]);
  // 控制省份的数据
  const [provinceList, setProvinceList] = useState<regionReturnResultType>([]);
  // 控制市的数据
  const [cityList, setCityList] = useState<regionReturnResultType>([]);
  // 控制地区的数据
  const [regionList, setRegionList] = useState<regionReturnResultType>([]);
  // 控制医院类型的数据
  const [HospitalGrade, setHospitalGrade] = useState<regionReturnResultType>(
    []
  );
  //控制重新渲染的state
  const [reRender, setReRender] = useState(true);
  // 1.1开始时获取详细信息 并监听page,limit,paramsList,reRender
  useEffect(() => {
    setIsLoading(true);
    const CallFunction = async () => {
      const res = await SendHospitalListRequest(page, limit, paramsList);
      setTableDate(res.content);
      setTotal(res.totalElements);
      setIsLoading(false);
    };
    CallFunction();
    // 监听下面state如果改变就重新渲染页面
  }, [page, limit, paramsList, reRender]);
  //1.2 开始的时候获取省份的数据
  useEffect(() => {
    const res = async () => {
      const re = await ProvinceInformationRequest();
      setProvinceList(re);
    };
    res();
  }, []);
  //1.3 开始的时候获取医院等级
  useEffect(() => {
    const res = async () => {
      const re = await GetRegionalDataRequest("10000");
      setHospitalGrade(re);
    };
    res();
  }, []);
  // 2.1当点击省的时候获取市的数据 顺便清空市级和区级的数据
  const getCityData = async (idList: string) => {
    const re = await GetRegionalDataRequest(idList);
    setCityList(re);
    form.setFieldsValue({ cityList: null, regionList: null });
    setRegionList([]);
  };
  // 2.2点击市级时获取区级的数据
  const getRegionData = async (idList: string) => {
    const re = await GetRegionalDataRequest(idList);
    // 重新点击的时候清空区级的数据
    form.setFieldsValue({ regionList: null });
    setRegionList(re);
  };
  // 2.3查询表单时的提交事件 搜索提交的数据时对应返回值的数据 是一一对应的
  const districtCode = (value: PagingListRequest) => {
    console.log(paramsList);
    console.log(value, "value");
    setParamsList(value);
    setPage(1);
  };
  // 2.4清空时
  const clearDate = () => {
    setParamsList({});
    // 搜索时自动跳到第一页
    setPage(1);
  };
  // 2.5点击上下线改变状态
  const ChangeState = (id: string, status: 0 | 1) => {
    return async () => {
      await ChangeStatusRequest(id, status);
      message.success(status ? "上线成功" : "下线成功");
      setReRender(!reRender);
    };
  };
  const columns = [
    {
      title: "序号",
      width: 60,
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render(logoData: string) {
        return <img width={120} src={`data:image/jpeg;base64,${logoData}`} />;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render(_: any, data: hospitalDateType) {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render(_: any, data: hospitalDateType) {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render(_: any, data: hospitalDateType) {
        return data.status === 0 ? "下线" : "上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 120,
      fixed: "right" as "right",
      render(_: any, data: hospitalDateType) {
        return (
          <div>
            <Button
              type="primary"
              // 点击查看的时候 进行param传参
              onClick={() => {
                navigate(`/syt/hospital/hospitalShow/${data.id}`);
              }}
            >
              查看
            </Button>
            <Button
              type="primary"
              onClick={() => {
                navigate(`/syt/hospital/hospitaldp/${data.hoscode}`);
              }}
            >
              排班
            </Button>
            {/* 点击时改变状态 */}
            <Button
              type="primary"
              onClick={ChangeState(data.id, data.status ? 0 : 1)}
            >
              {data.status ? "下线" : "上线"}
            </Button>
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Card>
        <Form
          name="basic"
          form={form}
          // 点击查看时 搜索符合条件的并重新渲染页面 跳转至第一页
          onFinish={districtCode}
        >
          <Row gutter={20}>
            <Col span={3}>
              <Form.Item name="provinceCode">
                <Select
                  placeholder="请选择省"
                  allowClear
                  onChange={getCityData}
                >
                  {provinceList.map((Item) => (
                    <Select.Option value={Item.value} key={Item.id}>
                      {Item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="cityCode">
                <Select
                  placeholder="请选择市"
                  allowClear
                  onChange={getRegionData}
                >
                  {cityList.map((Item) => (
                    <Select.Option value={Item.value} key={Item.id}>
                      {Item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="districtCode">
                <Select placeholder="请选择区" allowClear>
                  {regionList.map((Item) => (
                    <Select.Option value={Item.value} key={Item.id}>
                      {Item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="hosname">
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="hoscode">
                <Input placeholder="医院编号" />
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="hostype">
                <Select placeholder="医院类型" allowClear>
                  {HospitalGrade.map((Item) => {
                    return (
                      <Select.Option value={Item.value} key={Item.id}>
                        {Item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={3}>
              <Form.Item name="status">
                <Select placeholder="医院状态" allowClear>
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={1}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
            </Col>
            <Col span={1}>
              <Form.Item>
                <Button type="default" htmlType="reset" onClick={clearDate}>
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={tableData}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}
          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal(total) {
              return `总共有${total}条数据`;
            },
            onChange(current: number, pageSize: number) {
              setPage(current);
              setLimit(pageSize);
            },
          }}
        />
      </Card>
    </div>
  );
}
